import 'package:flutter/material.dart';
import 'package:flutter_base/common/sp_key.dart';
import 'package:flutter_base/common/user_helper.dart';
import 'package:flutter_base/http/api.dart';
import 'package:flutter_base/utils/sp_utils.dart';
import 'package:oktoast/oktoast.dart';

import '../../bean/login/user_info_entity.dart';

///
/// @DIR_PATH：lib/viewmodel/login
/// @TIME：2024/6/12 11:25
/// @AUTHOR：starr
/// 登录注册的按钮
///
class LoginViewModel with ChangeNotifier {
  //user/register
  RegisterInfo registerInfo = RegisterInfo();

  Future<bool?> register() async {
    if (registerInfo.name != null &&
        registerInfo.password != null &&
        registerInfo.rePassword != null &&
        registerInfo.password == registerInfo.rePassword) {
      if ((registerInfo.password?.length ?? 0) > 6) {
        dynamic callback = await Api.instance.register(
            name: registerInfo.name,
            password: registerInfo.password,
            rePassword: registerInfo.rePassword);
        if (callback is bool) {
          return callback;
        } else {
          return true;
        }
      }
      showToast("密码长度必须大于6");
      return false;
    }
    showToast("输入不能为空或者密码不一致");
    return false;
  }

  Future<bool?> login() async {
    UserInfoEntity? userInfo = await Api.instance
        .login(name: registerInfo.name, password: registerInfo.password);
    if (userInfo.username != null && userInfo.username?.isNotEmpty == true) {
      //保存用户名
      UserHelper.getInstance.userBean = userInfo;
      return true;
    }
    showToast("登录失败");
    return false;
  }
}

class RegisterInfo {
  String? name;
  String? password;
  String? rePassword;
}
